const { readdir, mkdir, copyFile } = require("node:fs/promises");
const { existsSync } = require("node:fs");
const path = require("path");

console.log("------------- Start 同步组件到ifun-ui -----------------");

const pathsToCheck = ["../uni_modules"];
// 需要同步的组件
const componentsName = [
  "ifun-tree-picker",
  "ifun-tree-select",
  "ifun-date-picker",
  "ifun-calendar",
];
// 读取uni_modules
pathsToCheck.forEach((val) => {
  let dir = path.resolve(__dirname, val);
  let bool = existsSync(dir);
  console.info(
    "目标路径地址:",
    dir,
    "------",
    bool ? "可访问读取" : "不可访问读取"
  );
  if (bool) {
    // 递归读取里面的ifun开头的组件
    readIfunComponent(dir);
  }
});
/**
 * 读取指定文件目录中的目标文件
 * 并写入目标目录文件中
 * @param {} path
 */
async function readIfunComponent(dir) {
  // 读取当前目录下的文件
  try {
    const files = await readdir(dir, { withFileTypes: true });
    for (const file of files) {
      if (file.isDirectory() && componentsName.includes(file.name)) {
        // 目录文件
        // 读取ifun-开头的文件目录，不为ifun-ui
        // 读取到的文件新建在ifun-ui/components目录下
        console.log("准备读取组件", file.name);
        await copyFileToIfunComoponent(
          path.join(dir, file.name, "components"),
          path.join(dir, "ifun-ui", "components")
        );
        console.log("准备读取静态资源", file.name);
        await copyFileToIfunComoponent(
          path.join(dir, file.name, "static"),
          path.join(dir, "ifun-ui", "static")
        );
        // await writeIfunComponent(file.name, "ifun-ui", path);
      }
    }
  } catch (err) {
    console.error(err);
  }
}
/**
 * 文件路径，
 * 目录则同样创建，然后读取目录文件，递归调用。
 * 文件则直接复制到相同目录下
 * @param {*} origin
 * @param {*} target
 */
async function copyFileToIfunComoponent(origin, target) {
  if (!existsSync(origin)) {
    return;
  }
  let files = await readdir(origin, {
    withFileTypes: true,
  });
  for (file of files) {
    if (file.isFile()) {
      // 是文件，直接复制
      console.log(`开始复制文件：`, file.name);
      await copyFile(
        path.join(origin, file.name),
        path.join(target, file.name)
      );
    }
    if (file.isDirectory()) {
      // 目录创建同名目录
      let targetPath = path.join(target, file.name);
      //
      console.log("开始创建目录：", file.name);
      await mkdir(targetPath, { recursive: true });
      // 递归读取
      await copyFileToIfunComoponent(path.join(origin, file.name), targetPath);
    }
  }
}
